import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { CreateAIMessageSession, DeleteAIMessageSession, GetAIMessageSessionList } from "@/api/ai.ts";
import { ElMessage } from "element-plus";
import { IAiMessageListItem, IAISession } from "@/types/ai";
import { useMitt } from "@/hooks/useMitt";
import { useCache } from "./cache";

export const UseAI = defineStore("ai", () => {
  const cache = useCache();

  let ActiveSessionId = ref<number | null>(null);
  let QuickChatSessionId = ref<string | null>(null);
  let AiSessionList = ref<IAISession[]>([]);
  let AiMessageList = ref<IAiMessageListItem[]>([]);
  let AiMessageType = ref<"message" | "new">("new");

  //获取会话列表
  async function GetSessionList() {
    const res: any = await GetAIMessageSessionList();
    if (!res || res.status != 200) return;
    res.data.forEach((session: IAISession) => {
      cache.AiMessageMapCache.set(session.id, session.messages);
    });
    AiSessionList.value = res.data;
  }

  //创建新会话
  async function AddNewSession(): Promise<number | void> {
    AiMessageType.value = "new";
    let result = await CreateSessionId();
    AiSessionList.value.unshift(result);
    ActiveSessionId.value = result.id;
    return ActiveSessionId.value!;
  }

  // 获取sessionId
  async function CreateSessionId() {
    const res: any = await CreateAIMessageSession();
    if (!res || res.status != 200) return;
    ActiveSessionId.value = res.data.sessionId;
    return res.data;
  }

  // 删除会话
  async function DeleteSession(sessionId: number) {
    let res: any = await DeleteAIMessageSession(sessionId);
    if (!res || res.status !== 200) return;
    if (ActiveSessionId.value === sessionId) {
      ActiveSessionId.value = null;
    }
    await GetSessionList();
    ElMessage.success("删除成功");
  }

  watch(
    () => ActiveSessionId.value,
    (newVal, oldVal) => {
      if (!newVal) {
        AiMessageList.value = [];
        return;
      }
      if (oldVal) cache.AiMessageMapCache.set(oldVal, AiMessageList.value);
      AiMessageList.value = cache.AiMessageMapCache.get(newVal) ?? [];
      useMitt.emit("aiChatScrollBottom");
    },
  );

  return {
    AiSessionList,
    GetSessionList,
    DeleteSession,
    AddNewSession,
    ActiveSessionId,
    AiMessageType,
    AiMessageList,
    CreateSessionId,
    QuickChatSessionId,
  };
});
